# -*- coding:utf-8 -*-

## ====================================================================
## Copyright (C) 2007-2011  Jean-Philippe GOLAY
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program; if not, write to the Free Software
## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
## =====================================================================


from Tkinter import *
import Pmw
from tkMessageBox import *

from Persistance import *
from iPlace import PlaceListGUI
from iReference import ReferenceListGUI

class ParkingGUI(Toplevel):
	def __init__(self, parent=None, balloon=None, path=None, log=None):
		Toplevel.__init__(self, parent)
		self.parent=parent
		self.grab_set()
		self.transient(self.master)
		self.resizable(width=False, height=False)
		self.title(u"Parking")
		self.balloon=balloon
		self.imgSearch=PhotoImage(file="img/search_icon.gif")
		self.imgSave=PhotoImage(file="img/save_icon.gif")
		self.imgDelete=PhotoImage(file="img/delete_icon.gif")
		self.path=path
		self.log=log
		# Afficher un icon personnalisé
		try:
			if os.name =="posix":
				img = PhotoImage(file=self.path+"/icons/Parking-icon.gif")
				self.tk.call("wm", "iconphoto", self._w, img)
			else:
				self.iconbitmap(default=self.path+"/icons/Parking-icon.gif")
		except TclError:
			self.log.warning("Le window manager ne supporte pas la jolie icône que je veux lui mettre... tant pis")
		self.log.info("\tParkingGUI\tStart")
		self.makeParking()

	# DEBUT de la gestion du module Parking ------------------------------------------------------------------------------------------------------------
	def clearFieldParking(self):
		# Mise a zéro des champs de la fiche emplois du temps
		self.parkingValues[0].set("")
		self.parkingValues[1].set("")
		self.parkingValues[2].set(u"E")
		self.parkingValues[3].set("")
		self.parkingTypeCB.selectitem(1)
		self.listObject=[Place, Reference]

	def selectParking(self, event):
		if self.listParking.get(0)!="":
			result = Parking.select(Parking.q.id==self.idListParking[int(self.listParking.curselection()[0])])
			for row in result:
				self.selectedParking = row
			self.listObject[0]=self.selectedParking.place
			self.listObject[1]=self.selectedParking.reference
			self.parkingValues[0].set(self.listObject[0].company)
			self.parkingValues[1].set(self.listObject[1].code)
			self.parkingValues[2].set(self.selectedParking.type)
			self.parkingValues[3].set(self.selectedParking.description)
			# Affichage du Type dans la ComboBox
			type = (("E", 0),("I", 1),)
			for n in type:
				if n[0] == self.selectedParking.type: self.parkingTypeCB.selectitem(n[1])
			# activation du bouton supprimer
			self.deleteParkingBt.config(state=NORMAL)

	def searchParking(self, event=None):
		if self.searchParkingValue.get() != "":
			self.listParking.delete(0,END)
			self.idListParkinge = []
			result = Parking.select(Parking.q.description.startswith(self.searchParkingValue.get().encode("utf-8")), orderBy=Parking.q.description)
			for row in result:
				self.listParking.insert(END, row.place.company+" - "+row.description)
				self.idListParking.append(row.id)
		else:
			self.listParking.delete(0,END)
			self.idListParking = []
			result = Parking.select(orderBy=Parking.q.description)
			for row in result:
				self.listParking.insert(END, row.place.company+" - "+row.description)
				self.idListParking.append(row.id)

	def makeParking(self):
		leftFrame = Frame(self)
		# Fiche Parking  (présentation colonne de gauche)
		Label(leftFrame, text=u"Fiche Parking").pack(side=TOP, fill=X)
		# Création des champs a renseigner pour un object Parking
		parkingLabels = (u"Résidence", u"Référence", u"Type", u"Déscription")
		self.parkingValues = [StringVar(), StringVar(), StringVar(), StringVar()]
		parkingTypeCB = ("Exterieur","Interieur")
		count = 0
		for name in parkingLabels:
			f = Frame(leftFrame)
			Label(f, width=12, text=name, anchor=W).pack(side=LEFT)
			if count == 0: # Résidence
				Entry(f, textvariable=self.parkingValues[count], width=25, state=DISABLED, bd=0, disabledforeground="black").pack(side=LEFT, fill=X)
				myPlace=Button(f, image=self.imgSearch, command=lambda x=self.parkingValues[count]:self.ctrlListPlace(x), padx=4, pady=1)
				myPlace.pack(side=RIGHT)
				self.balloon.bind(myPlace, u"Choisir une Résidence")
			elif count == 1: # Référence
				Entry(f, textvariable=self.parkingValues[count], width=25, state=DISABLED, bd=0, disabledforeground="black").pack(side=LEFT, fill=X)
				myReference=Button(f, image=self.imgSearch, command=lambda x=self.parkingValues[count]:self.ctrlListReference(x), padx=4, pady=1)
				myReference.pack(side=RIGHT)
				self.balloon.bind(myReference, u"Choisir une Référence")
			elif count == 2: # Type
				self.parkingTypeCB=Pmw.ComboBox(f, selectioncommand=self.parkingType, scrolledlist_items=parkingTypeCB, listheight=100)
				self.parkingTypeCB.pack(side=LEFT, fill=X)
				self.parkingTypeCB._entryfield._entryFieldEntry.config( width = 25)
				self.parkingTypeCB.selectitem(1)
				self.parkingValues[count].set(u"E")
			else: # Déscription
				Entry(f, textvariable=self.parkingValues[count], width=28).pack(side=LEFT, fill=X)
			f.pack(side=TOP, fill=X)
			count += 1
		# Boutons enregistrement (new ou modify) et suppression
		s = Frame(leftFrame) 
		self.saveParkingBt=Button(s, image=self.imgSave, command=self.createParking)
		self.saveParkingBt.bind("<Return>", self.createParking)
		self.saveParkingBt.pack(side=LEFT)
		self.balloon.bind(self.saveParkingBt, u"Enregistrer")
		self.deleteParkingBt=Button(s, image=self.imgDelete, command=self.deleteParking, state=DISABLED)
		self.deleteParkingBt.bind("<Return>", self.deleteParking)
		self.deleteParkingBt.pack(side=LEFT)
		self.balloon.bind(self.deleteParkingBt, u"Supprimer")
		s.pack(side=TOP, fill=X)
		leftFrame.pack(side=LEFT, fill=X)
		Label(leftFrame, text=u"Liste des Parkings").pack(side=TOP, fill=X)
		self.searchParkingValue = StringVar()
		self.searchParkingEt = Entry(leftFrame,  width=40, textvariable=self.searchParkingValue, relief=GROOVE)
		self.searchParkingEt.bind("<KeyRelease>", self.searchParking)
		self.searchParkingEt.pack(side=TOP, fill=X)
		self.balloon.bind(self.searchParkingEt, u"Saisir les premières lettres d'un Parking\npour une recherche plus précise,\nla liste est classée par Déscription.")
		s = Frame(leftFrame) 
		scrollbar = Scrollbar(s)
		scrollbar.pack(side=RIGHT, fill=Y)
		self.listParking = Listbox(s)
		self.listParking.config(yscrollcommand=scrollbar.set, width=40, selectmode=SINGLE, height=16)
		self.listParking.bind("<ButtonRelease-1>",self.selectParking)
		scrollbar.config(command=self.listParking.yview)
		self.listParking.pack()
		self.balloon.bind(self.listParking, u"Séléctionner un Parking\npour le visualiser ou la modifier.")
		s.pack(side=TOP, fill=X)
		leftFrame.pack(side=LEFT, fill=X)
		# Initialisation
		self.clearFieldParking()
		self.searchParking()

	def ctrlListPlace(self,field):
		PlaceListGUI(balloon=self.balloon, field=field, index=0, listObject=self.listObject, log=self.log, path=self.path)

	def ctrlListReference(self,field):
		ReferenceListGUI(balloon=self.balloon, field=field, index=1, listObject=self.listObject, log=self.log, path=self.path)

	def parkingType(self, value):
		type = (("E", "Exterieur"),("I", "Interieur"),)
		for n in type:
			if n[1] == value: self.parkingValues[2].set(n[0])

	def verifyParking(self):
		if self.parkingValues[0].get() == "":
			showerror(u"Erreur de saisie", u"Le champ Résidence est obligatoire !\nMerci de le compléter.")
			return False
		elif self.parkingValues[1].get() == "":
			showerror(u"Erreur de saisie", u"Le champ Référence est obligatoire !\nMerci de le compléter.")
			return False
		elif self.parkingValues[2].get() == "": 
			showerror(u"Erreur de saisie", u"Le champ Type est obligatoire !\nMerci de le compléter.")
			return False
		elif self.parkingValues[3].get() == "": 
			showerror(u"Erreur de saisie", u"Le champ Déscription est obligatoire !\nMerci de le compléter.")
			return False
		else:
			return True

	def createParking(self, event=None):
		if self.verifyParking():
			if  self.deleteParkingBt.config()["state"][4] == "normal":
				self.modifyParking()
			else:
				if askyesno(u"Enregistrement", u"Souhaitez-vous enregistrer %s comme un nouveau Parking ?\n" % self.parkingValues[3].get()):
					Parking(place=self.listObject[0],
						reference=self.listObject[1],
						type=self.parkingValues[2].get().encode("utf-8"),
						description=self.parkingValues[3].get().encode("utf-8"),
						createDate=datetime.datetime.now()
					)
					self.searchParking()
				self.clearFieldParking()

	def modifyParking(self, event=None): 
		if askyesno(u"Modifier", u"Souhaitez-vous modifier le Parking %s ?" % self.selectedParking.description):
			self.selectedParking.place=self.listObject[0]
			self.selectedParking.reference=self.listObject[1]
			self.selectedParking.type=self.parkingValues[2].get().encode("utf-8")
			self.selectedParking.description=self.parkingValues[3].get().encode("utf-8")
			self.searchParking()
		self.deleteParkingBt.config(state=DISABLED)
		self.clearFieldParking()

	def deleteParking(self, event=None): 
		if askyesno(u"Suppression", u"Souhaitez-vous supprimer le Parking %s ?\nCette opération est irréversible !" % self.selectedParking.description):
			Parking.delete(self.selectedParking.id)
			self.searchParking()            
		self.deleteParkingBt.config(state=DISABLED)
		self.clearFieldParking()
	# FIN de la gestion du module Parking -------------------------------------------------------------------------------------------------------------------

class ParkingListGUI(Toplevel):
	def __init__(self, parent=None, balloon=None, field=None, index=None, indexPlace=None, listObject=None, path=None, log=None):
		Toplevel.__init__(self, parent)
		self.parent=parent
		self.grab_set()
		self.transient(self.master)
		self.resizable(width=False, height=False)
		self.title(u"Liste des Parkings")
		self.balloon=balloon
		self.imgNew=PhotoImage(file="img/add_alternative_icon.gif")
		self.field=field
		self.index=index
		self.indexPlace=indexPlace
		self.listObject=listObject
		self.path=path
		self.log=log
		# Afficher un icon personnalisé
		try:
			if os.name =="posix":
				img = PhotoImage(file=self.path+"/icons/Parking-icon.gif")
				self.tk.call("wm", "iconphoto", self._w, img)
			else:
				self.iconbitmap(default=self.path+"/icons/Parking-icon.gif")
		except TclError:
			self.log.warning("Le window manager ne supporte pas la jolie icône que je veux lui mettre... tant pis")
		self.log.info("\tParkingListGUI\tStart")
		self.makeListParking()

	def selectListParking(self, event):
		if self.listListParking.get(0)!="":
			result = Parking.select(Parking.q.id==self.idListListParking[int(self.listListParking.curselection()[0])])
			for row in result:
				self.listObject[self.index]=row
				self.field.set(row.type+" - "+row.description)
				self.destroy()

	def searchListParking(self, event=None):
		if self.searchListParkingValue.get() != "":
			self.listListParking.delete(0,END)
			self.idListListParking = []
			if self.listObject[self.indexPlace] != Place:
				result = Parking.select(AND(Parking.q.description.startswith(self.searchListParkingValue.get().encode("utf-8")), Parking.q.place==self.listObject[self.indexPlace]), orderBy=Parking.q.description)
			else:
				result = Parking.select(Parking.q.description.startswith(self.searchListParkingValue.get().encode("utf-8")), orderBy=Parking.q.description)
			for row in result:
				self.listListParking.insert(END, row.type+" - "+row.description+" - "+row.place.company)
				self.idListListParking.append(row.id)
		else:
			self.listListParking.delete(0,END)
			self.idListListParking = []
			if self.listObject[self.indexPlace] != Place:
				result = Parking.select(Parking.q.place==self.listObject[self.indexPlace], orderBy=Parking.q.description)
			else:
				result = Parking.select(orderBy=Parking.q.description)
			for row in result:
				self.listListParking.insert(END, row.type+" - "+row.description+" - "+row.place.company)
				self.idListListParking.append(row.id)

	def makeListParking(self):
		leftFrame = Frame(self)
		Label(leftFrame, text=u"Liste des places de Parking").pack(side=TOP, fill=X)
		self.searchListParkingValue = StringVar()
		s = Frame(leftFrame) 
		self.searchListParkingEt = Entry(s,  width=39, textvariable=self.searchListParkingValue, relief=GROOVE)
		self.searchListParkingEt.bind("<KeyRelease>", self.searchListParking)
		self.searchListParkingEt.pack(side=LEFT, fill=X)
		self.balloon.bind(self.searchListParkingEt, u"Saisir les premiéres lettres de la désignation d'un Parking\npour une recherche plus précise,\nla liste est classée par numéros.")
		newParkingBt=Button(s, image=self.imgNew, command=self.ctrlParking)
		newParkingBt.pack(side=RIGHT)
		self.balloon.bind(newParkingBt, u"Créer une nouvelle place de Parking")
		s.pack(side=TOP, fill=X)
		s = Frame(leftFrame) 
		scrollbar = Scrollbar(s)
		scrollbar.pack(side=RIGHT, fill=Y)
		self.listListParking = Listbox(s)
		self.listListParking.config(yscrollcommand=scrollbar.set,width=40, selectmode=SINGLE, height=16)
		self.listListParking.bind("<ButtonRelease-1>",self.selectListParking)
		scrollbar.config(command=self.listListParking.yview)
		self.listListParking.pack()
		self.balloon.bind(self.listListParking, u"Séléctionner un Parking.")
		s.pack(side=TOP, fill=X)
		leftFrame.pack()
		self.searchListParking()
		
	def ctrlParking(self):
		ParkingGUI(balloon=self.balloon, log=self.log, path=self.path)